// 构造函数的参数是一个异步任务 
// Promise构造函数
// tast也是一个回调函数
function Promise(task) {
    this.status = 'pending'
    this.value = undefined
    this.onresolvedCallbacks = []
    this.onrejectedCallbacks = []
    // resolve将来有用户成功时候调用

    let resolve = value => {
        // console.log(this)function定义函数函this是node执行环境
        // 用了箭头函数指代外层函数中this 正好是promise实例
        // console.log(this.status)
        if (this.status == 'pending') {
            this.status = 'fulfilled'
            this.value = value
            // 函数内部自动执行onresolved方法
            this.onresolvedCallbacks.forEach(element => element(value))
        }
    }
    // 将来用户失败时候调用
    let reject = err => {
        // 只有promise实例对象是pending时，才能改变转账
        if (this.status == 'pending') {
            this.status = 'rejected'
            this.value = err
            this.onrejectedCallbacks.forEach(element => element(err))
        }
    }

    task(resolve, reject)

}
Promise.prototype.then = function (onresolved, onrejected) {
    // 不需等待支持同步
    if(this.status=='fulfilled'){
        onresolved(this.value)
    }
    if(this.status=='rejected'){
        onrejected(this.value)
    }
    if(this.status=='pending'){
        this.onresolvedCallbacks.push(onresolved)
        this.onrejectedCallbacks.push(onrejected)

    }

}
module.exports = Promise